package com.example.demo.thread;

/**
 * @Description:
 * @Author: xiatian
 * @CreateTime: 2021/7/23
 * @Company: kangxu
 */
public class Singleton {
    //使用volatile修饰，保持所有的线程同步，防止指令重排序导致还没有初始化instance就获去instance对象
    private volatile static Singleton instance;


    private Singleton() {

    }

    public static Singleton getInstance() {
        //判断是否实例过，没有的话进入到加锁代码
        if (instance == null) {
            //给类加锁
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}
